//
//  HomeController.swift
//  CreateMyCode
//
//  Created by zhibao on 2024/2/1.
//

import UIKit
import SnapKit
class HomeController:SuperController{
    
    fileprivate var titleField = QMUITextField()
    fileprivate var textView = QMUITextView()
    fileprivate var selectQrCode = [String:Any]()
    fileprivate var showScrollview = UIScrollView()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if UserDefaults.standard.value(forKey: "privacy1") == nil {
            Helper.privacyAgreementShow()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        UserInfoManager.shared().userInit()
        let saoMBtn = UIButton(type: .custom)
        saoMBtn.frame = CGRectMake(0, 0, pixw(p:80), pixw(p:60))
        saoMBtn.addTarget(self, action: #selector(saomiaoClick), for: .touchUpInside)
        saoMBtn.setTitle("扫描识别->", for: .normal)
        saoMBtn.setTitleColor(MYBlock, for: .normal)
        saoMBtn.titleLabel?.font = MY_SCALE_BoldFont(15)
        let item = UIBarButtonItem(customView: saoMBtn)
        self.gk_navRightBarButtonItems = [item]
        self.getPayInfo()
        self.initView()
    }
    
    @objc fileprivate func saomiaoClick(){
        let controller = SaoIngController()
        self.navigationController?.pushViewController(controller, animated: true)
    }
    
    fileprivate func getPayInfo(){
        if IAPShare.sharedHelper().iap == nil {
            let dataSet = NSSet(array: ["com.yuliang.year","com.yuliang.ji","com.yuliang.yue","com.yuliang.zhou"])
            IAPShare.sharedHelper().iap = IAPHelper(productIdentifiers: dataSet as? Set<AnyHashable>)
        }
        IAPShare.sharedHelper().iap.requestProducts { request, response in
            DLog(message: "response1==\(String(describing: response?.products))")
        }
        IAPShare.sharedHelper().iap.production = false
    }
    
    func initView() {
        let iconImgView = UIImageView(image: UIImage(named: "com_icon"))
        iconImgView.layer.masksToBounds = true
        iconImgView.layer.cornerRadius = 5
        self.view.addSubview(iconImgView)
        iconImgView.snp.makeConstraints { make in
            make.width.height.equalTo(80)
            make.centerX.equalTo(self.view)
            make.top.equalTo(navigationFullHeight() + 20)
        }
        
        //标题
        titleField = QMUITextField()
        titleField.maximumTextLength = 10
        titleField.layer.cornerRadius = pixw(p: 5)
        titleField.layer.borderColor = MYColor.color(withHexString: "cacaca").cgColor
        titleField.layer.borderWidth = pixw(p: 0.5)
        titleField.font = MY_SCALE_BoldFont(14)
        titleField.placeholder = LocalizedString("请输入标题（10字以内）(选填)")
        titleField.textInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        titleField.placeholderColor = MYColor.color(withHexString: "999999")
        titleField.textColor = MYColor.color(withHexString: "333333")
        self.view.addSubview(titleField)
        titleField.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(iconImgView.snp.bottom).offset(30)
        }
        
        textView = QMUITextView()
        textView.layer.cornerRadius = pixw(p: 5)
        textView.layer.borderColor = MYColor.color(withHexString: "cacaca").cgColor
        textView.layer.borderWidth = pixw(p: 0.5)
        textView.placeholder = LocalizedString(" 请输入内容")
        textView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        textView.font = MY_SCALE_RegularFONT(12)
        textView.placeholderColor = MYColor.color(withHexString: "999999")
        textView.textColor = MYColor.color(withHexString: "333333")
        textView.backgroundColor = UIColor.clear
        textView.limitLength = NSNumber(integerLiteral: 100)
        textView.limitPlaceColor = MYColor.color(withHexString: "999999")
        self.view.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.left.right.equalTo(titleField)
            make.top.equalTo(titleField.snp.bottom).offset(20)
            make.height.equalTo(pixw(p: 100))
        }
        
        let nextBtn = UIButton(type: .custom)
        nextBtn.backgroundColor = MYBlue
        nextBtn.layer.cornerRadius = pixw(p: 5)
        nextBtn.setTitle(LocalizedString("创建二维码"), for: .normal)
        nextBtn.setTitleColor(UIColor.white, for: .normal)
        nextBtn.setTitleShadowColor(MYBlue, for: .normal)
        nextBtn.titleLabel?.font = MY_SCALE_SemiboldFONT(16)
        self.view.addSubview(nextBtn)
        nextBtn.addTarget(self, action: #selector(nextClick), for: .touchUpInside)
        nextBtn.snp.makeConstraints { make in
            make.left.right.equalTo(textView)
            make.height.equalTo(pixw(p: 45))
            make.top.equalTo(textView.snp.bottom).offset(30)
        }
        
        let yangliLabel = UILabel()
        yangliLabel.text = LocalizedString("样例展示")
        yangliLabel.textColor = UIColor.black
        yangliLabel.font = MY_SCALE_BoldFont(14)
        self.view.addSubview(yangliLabel)
        yangliLabel.snp.makeConstraints { make in
            make.left.equalTo(textView)
            make.top.equalTo(nextBtn.snp.bottom).offset(30)
        }
        
        let yangliTipLabel = UILabel()
        yangliTipLabel.text = LocalizedString("(点击直接使用↓)")
        yangliTipLabel.textColor = MYBlock
        yangliTipLabel.font = MY_SCALE_HeavyFONT(9)
        self.view.addSubview(yangliTipLabel)
        yangliTipLabel.snp.makeConstraints { make in
            make.left.equalTo(yangliLabel.snp.right).offset(4)
            make.centerY.equalTo(yangliLabel)
        }
        
        showScrollview = UIScrollView()
        showScrollview.showsHorizontalScrollIndicator = false
        self.view.addSubview(showScrollview)
        showScrollview.snp.makeConstraints { make in
            make.left.right.equalTo(titleField)
            make.top.equalTo(yangliLabel.snp.bottom).offset(10)
            make.height.equalTo(pixw(p: 80))
        }
        
        let bottomLabel = YYLabel()
        bottomLabel.lineBreakMode = .byWordWrapping
        bottomLabel.numberOfLines = 0
        bottomLabel.preferredMaxLayoutWidth = SCREEN_WIDTH - 60
        self.view.addSubview(bottomLabel)
        bottomLabel.snp.makeConstraints { make in
            make.left.right.equalTo(textView)
            make.top.equalTo(showScrollview.snp.bottom).offset(20)
        }
        
        let string = NSMutableString()
        string.append(LocalizedString("温馨提示:\n创建二维码后，可对样式进行重新选择，包含模版、颜色、点阵、码眼、图标以及文字等。"))
        let tip1Str = LocalizedString("\n\n特别说明：")
        let tip2Str = LocalizedString("Vip会员生成的任意二维码长期有效，永久不加广告、跳转链接等！")
        string.append(tip1Str)
        string.append("\n")
        string.append(tip2Str)
        let tip1Range = string.range(of: tip1Str)
        let tip2Range = string.range(of: tip2Str)
        
        
        let attri = NSMutableAttributedString(string: string as String)
        attri.yy_font = MY_SCALE_RegularFONT(11)
        attri.yy_color = MYColor.color(withHexString: "666666")
        attri.yy_setFont(MY_SCALE_BoldFont(13), range: tip1Range)
        attri.yy_setColor(MYRed, range: tip1Range)
        attri.yy_setFont(MY_SCALE_BoldFont(12), range: tip2Range)
        attri.yy_setColor(MYRed, range: tip2Range)
        bottomLabel.attributedText = attri
        self.getData()
    }
    
    @objc func nextClick(){
        if textView.text.qmui_trimAllWhiteSpace.count < 1 {
            QMUITips.showError(LocalizedString(" 请输入内容"))
            return
        }
        
        if (!UserInfoManager.shared().isVip()) && (MYGlobal.share().wechatFlag != 1){
            Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("开通该会员才能保存哦！"), withSureBtnTitle: LocalizedString("开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                if index == 1 {
                    let controller = PayMarkController()
                    self.navigationController?.pushViewController(controller, animated: true)
                }
            }
          return
        }
        
        var qrDic = [String:Any]()
        qrDic["nav"] = titleField.text?.qmui_trimAllWhiteSpace.count ?? 0 > 0 ? titleField.text!.qmui_trimAllWhiteSpace : "---"
        var tempQrDic = [String:Any]()
        tempQrDic["qrCategory"] = "text"
        tempQrDic["text"] = textView.text.qmui_trimAllWhiteSpace
        tempQrDic["size"] = NSNumber(integerLiteral: 500)
        tempQrDic["colorDark"] = "#000000"
        
        if selectQrCode.keys.count > 0 {
            if (selectQrCode["backgroundColor"] != nil) {
                tempQrDic["backgroundColor"] = selectQrCode["backgroundColor"]
            }
            
            if (selectQrCode["colorDark"] != nil) {
                tempQrDic["colorDark"] = selectQrCode["colorDark"]
            }
            
            if (selectQrCode["eye_inner"] != nil) {
                tempQrDic["eye_inner"] = selectQrCode["eye_inner"]
            }
            
            if (selectQrCode["eye_outer"] != nil) {
                tempQrDic["eye_outer"] = selectQrCode["eye_outer"]
            }
            
            if (selectQrCode["qrData"] != nil) {
                tempQrDic["qrData"] = selectQrCode["qrData"]
            }
        }
        qrDic["qrCode"] = tempQrDic
        qrDic["type"] = "0"
        
        QRNetHelper.sharedInstance().sendPost("qrcodes/qr2", parameters: tempQrDic) { operation, responseObject in
            let repData1 = responseObject.data as! [String:Any]
            
            var dic = [String:Any]()
            dic["url"] = repData1["url"]
            dic["content"] = self.textView.text.qmui_trimAllWhiteSpace
            dic["type"] = qrDic["type"]
            dic["customParameterStr"] = Helper.convert(toJSONData: qrDic)
            let controller = EditCodeController()
            controller.editDic = dic
            DLog(message: "22222===\(dic)")
            self.navigationController?.pushViewController(controller, animated: true)
        } failure: { operation, error in
            
        }

    }
    
    fileprivate func getData(){
        HttpHelper.sharedInstance().sendGet("api/template/hot", parameters: [:]) { operation, responseObject in
            if responseObject.code == 1 {
                let repData1 = responseObject.data as! [String:Any]
                DLog(message: "eeee===\(repData1)")
                let data = repData1["data"] as? [[String:Any]] ?? [[String:Any]]()
                var tempView:UIView?
                for i in 0 ..< data.count {
                    let dic = data[data.count - 1 - i]
                    let imgView = UIImageView()
                    imgView.isUserInteractionEnabled = true
                    imgView.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
                        let default_parameters = dic["default_parameters"]! as! [String:Any]
                        self.selectQrCode = default_parameters["qrCode"]! as! [String:Any]
                        self.nextClick()
                    }))
                    let demo_url = dic["demo_url"]! as! String
                    let urlStr = demo_url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
                    imgView.yy_setImage(with: URL(string: urlStr ?? ""))
                    self.showScrollview.addSubview(imgView)
                    imgView.snp.makeConstraints { make in
                        if(i == 0){
                            make.left.equalTo(0)
                        }else{
                            make.left.equalTo(tempView!.snp.right).offset(pixw(p: 10))
                        }
                        
                        if(i == data.count - 1){
                            make.right.equalTo(self.showScrollview)
                        }
                        make.top.equalTo(0)
                        make.width.height.equalTo(pixw(p: 80))
                    }
                    tempView = imgView
                }
            }
        } failure: { operation, error in
            
        }

    }
}
